package com.gmail.at.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gmail.at.form.TrainGrid;
import com.gmail.at.model.Train;
import com.gmail.at.service.TrainService;
import com.google.common.collect.Lists;

@RequestMapping("/trains")
@Controller
public class TrainController {
	
	final Logger logger = LoggerFactory.getLogger(TrainController.class);
	
	@Autowired
	private TrainService trainService;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(method = RequestMethod.GET)
	public String list(Model uiModel) {
		logger.info("Listing trains");
		Train train = new Train();
		uiModel.addAttribute("train", train);
		return "trains/list";
	}
	
	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public TrainGrid listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order) {
		logger.info("Listing trains for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing trains for grid with sort: {}, order: {}",
				sortBy, order);
		Sort sort = null;
		String orderBy = sortBy;
		if (orderBy != null && order != null) {
			if (order.equals("desc")) {
				sort = new Sort(Sort.Direction.DESC, orderBy);
			} else
				sort = new Sort(Sort.Direction.ASC, orderBy);
		}
		PageRequest pageRequest = null;
		if (sort != null) {
			pageRequest = new PageRequest(page - 1, rows, sort);
		} else {
			pageRequest = new PageRequest(page - 1, rows);
		}
		Page<Train> trainPage = trainService.findAllByPage(pageRequest);
		TrainGrid trainGrid = new TrainGrid();
		trainGrid.setCurrentPage(trainPage.getNumber() + 1);
		trainGrid.setTotalPages(trainPage.getTotalPages());
		trainGrid.setTotalRecords(trainPage.getTotalElements());
		trainGrid.setTrainData(Lists.newArrayList(trainPage.iterator()));
		return trainGrid;
	}
	
	
	
	@RequestMapping(value = "/{trainID}", params = "delete", method = RequestMethod.GET)
	public @ResponseBody String delete(@PathVariable("trainID") Integer id, Model uiModel) {
		return trainService.delete(id);
	}
	
	@RequestMapping(value = "/{trainID}", params = "form", method = RequestMethod.POST)
	public @ResponseBody String update(@Valid Train train, @PathVariable("trainID") Integer id, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Updating trains");
		if (bindingResult.hasErrors()) {
			return "Invalid train information (check train number)";
		}
		Train temp = trainService.findById(id);
		if (temp != null) {
			if (temp.getTrainNumber() == train.getTrainNumber()) {
				if (temp.getPlaces() == train.getPlaces()) {
					return "ok";
				} else {
					temp.setPlaces(train.getPlaces());
					trainService.delete(id);
					trainService.save(temp);
					return "ok";
				}		
			}
			temp.setTrainNumber(train.getTrainNumber());
			temp.setPlaces(train.getPlaces());
			Train result = trainService.save(temp);
			if (result == null) {
				return "This train number already exists!";
			} else {
				return "ok";
			}
		} else {
			return "Train with this id wasn't found, update your list";
		}
	}
	
	
	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody String create(@Valid Train train, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Creating train");
		if (bindingResult.hasErrors()) {
			return "Invalid train information (check fields)";
		}
		Train result = trainService.save(train);
    	if (result == null) {
    		return "This train number already exists!";	 
    	} else {
    		return "ok";  
    	}
	}
}
